<template>
  <div class="role-management">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">
          <i class="el-icon-s-custom"></i>
          角色管理
        </h2>
        <span class="page-subtitle">管理系统角色和权限分配</span>
      </div>
      <div class="header-actions">
        <el-button 
          type="primary" 
          icon="el-icon-plus" 
          @click="handleAdd" 
          v-if="hasPermission('system:role:add')"
          size="medium"
        >
          新增角色
        </el-button>
        <el-button 
          icon="el-icon-download" 
          @click="handleExport" 
          v-if="hasPermission('system:role:export')"
          size="medium"
        >
          导出数据
        </el-button>
        <el-button 
          icon="el-icon-refresh" 
          @click="loadData"
          :loading="loading"
          size="medium"
        >
          刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <el-card shadow="never" class="search-card">
        <el-form :model="searchForm" :inline="true" class="search-form">
          <el-form-item label="角色名称">
            <el-input
              v-model="searchForm.roleName"
              placeholder="请输入角色名称"
              clearable
              prefix-icon="el-icon-search"
              @keyup.enter.native="handleSearch"
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="角色类型">
            <el-select 
              v-model="searchForm.roleType" 
              placeholder="请选择角色类型" 
              clearable
              style="width: 150px"
            >
              <el-option label="系统角色" value="system" />
              <el-option label="业务角色" value="business" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select 
              v-model="searchForm.status" 
              placeholder="请选择状态" 
              clearable
              style="width: 120px"
            >
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleSearch">
              搜索
            </el-button>
            <el-button icon="el-icon-refresh" @click="handleReset">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 数据表格区域 -->
    <div class="table-section">
      <el-card shadow="never" class="table-card">
        <!-- 表格工具栏 -->
        <div class="table-toolbar">
          <div class="toolbar-left">
            <span class="table-title">角色列表</span>
            <el-tag v-if="selectedRows.length > 0" type="info" size="small">
              已选择 {{ selectedRows.length }} 项
            </el-tag>
          </div>
          <div class="toolbar-right">
            <el-button 
              size="small" 
              type="primary"
              :icon="showRoleTree ? 'el-icon-menu' : 'el-icon-s-grid'"
              @click="showRoleTree = !showRoleTree"
              class="view-toggle-btn"
            >
              {{ showRoleTree ? '列表视图' : '树形视图' }}
            </el-button>
          </div>
        </div>

        <!-- 树形视图 -->
        <div v-if="showRoleTree" class="tree-view">
          <el-tree
            :data="roleTreeData"
            :props="treeProps"
            node-key="id"
            :expand-on-click-node="false"
            :default-expand-all="true"
            class="role-tree"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span class="tree-node-label">
                <i :class="data.roleType === 'system' ? 'el-icon-setting' : 'el-icon-user'"></i>
                {{ data.roleName }}
                <el-tag 
                  :type="data.status === 1 ? 'success' : 'danger'" 
                  size="mini" 
                  style="margin-left: 8px"
                >
                  {{ data.status === 1 ? '启用' : '禁用' }}
                </el-tag>
              </span>
              <span class="tree-node-actions">
                <el-button 
                  size="mini" 
                  type="text" 
                  icon="el-icon-view"
                  @click="handleView(data)"
                  v-if="hasPermission('system:role:list')"
                >
                  查看
                </el-button>
                <el-button 
                  size="mini" 
                  type="text" 
                  icon="el-icon-edit"
                  @click="handleEdit(data)"
                  v-if="hasPermission('system:role:edit')"
                >
                  编辑
                </el-button>
                <el-button 
                  size="mini" 
                  type="text" 
                  icon="el-icon-user"
                  @click="handleAssignUsers(data)"
                  v-if="hasPermission('system:role:assign')"
                >
                  分配用户
                </el-button>
                <el-button 
                  size="mini" 
                  type="text" 
                  icon="el-icon-key"
                  @click="handleAssignPermissions(data)"
                  v-if="hasPermission('system:role:assign')"
                >
                  分配权限
                </el-button>
                <el-button 
                  size="mini" 
                  type="text" 
                  icon="el-icon-delete"
                  @click="handleDelete(data)"
                  v-if="hasPermission('system:role:delete')"
                  style="color: #f56c6c"
                >
                  删除
                </el-button>
              </span>
            </span>
          </el-tree>
        </div>

        <!-- 列表视图 -->
        <div v-else>
          <!-- 数据表格 -->
          <el-table
            :data="tableData"
            v-loading="loading"
            @selection-change="handleSelectionChange"
            stripe
            border
            height="500"
            class="data-table"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="id" label="ID" width="80" align="center" />
            <el-table-column prop="roleName" label="角色名称" width="150" show-overflow-tooltip />
            <el-table-column prop="roleCode" label="角色编码" width="120" show-overflow-tooltip />
            <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
            <el-table-column prop="roleType" label="角色类型" width="100" align="center">
              <template slot-scope="scope">
                <el-tag :type="scope.row.roleType === 'system' ? 'primary' : 'success'" size="small">
                  {{ scope.row.roleType === 'system' ? '系统角色' : '业务角色' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="80" align="center">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="small">
                  {{ scope.row.status === 1 ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="userCount" label="用户数量" width="120" align="center">
              <template slot-scope="scope">
                <div class="user-count-container">
                  <el-badge :value="scope.row.userCount || 0" class="user-count-badge" :max="99">
                    <el-button size="mini" type="text" @click="handleViewUsers(scope.row)">
                      <i class="el-icon-user"></i> 用户
                    </el-button>
                  </el-badge>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="160" show-overflow-tooltip />
            <el-table-column label="操作" width="250" fixed="right" align="center">
              <template slot-scope="scope">
                <el-button 
                  size="mini" 
                  icon="el-icon-view" 
                  @click="handleView(scope.row)" 
                  v-if="hasPermission('system:role:list')"
                  type="text"
                >
                  查看
                </el-button>
                <el-button 
                  size="mini" 
                  icon="el-icon-edit" 
                  @click="handleEdit(scope.row)" 
                  v-if="hasPermission('system:role:edit')"
                  type="text"
                >
                  编辑
                </el-button>
                <el-button 
                  size="mini" 
                  icon="el-icon-user" 
                  @click="handleAssignUsers(scope.row)" 
                  v-if="hasPermission('system:role:assign')"
                  type="text"
                >
                  分配用户
                </el-button>
                <el-button 
                  size="mini" 
                  icon="el-icon-key" 
                  @click="handleAssignPermissions(scope.row)" 
                  v-if="hasPermission('system:role:assign')"
                  type="text"
                >
                  分配权限
                </el-button>
                <el-button 
                  size="mini" 
                  icon="el-icon-delete" 
                  @click="handleDelete(scope.row)" 
                  v-if="hasPermission('system:role:delete')"
                  type="text"
                  style="color: #f56c6c"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pagination.page"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="pagination.size"
              :total="pagination.total"
              layout="total, sizes, prev, pager, next, jumper"
              background
            />
          </div>
        </div>
      </el-card>
    </div>

    <!-- 批量操作 -->
    <div class="batch-actions" v-if="selectedRows.length > 0">
      <el-card shadow="never" class="batch-card">
        <div class="batch-content">
          <span class="batch-info">
            <i class="el-icon-info"></i>
            已选择 {{ selectedRows.length }} 个角色
          </span>
          <div class="batch-buttons">
            <el-button 
              type="success" 
              icon="el-icon-check" 
              @click="handleBatchEnable" 
              v-if="hasPermission('system:role:edit')"
              size="small"
            >
              批量启用
            </el-button>
            <el-button 
              type="warning" 
              icon="el-icon-close" 
              @click="handleBatchDisable" 
              v-if="hasPermission('system:role:edit')"
              size="small"
            >
              批量禁用
            </el-button>
            <el-button 
              type="danger" 
              icon="el-icon-delete" 
              @click="handleBatchDelete" 
              v-if="hasPermission('system:role:delete')"
              size="small"
            >
              批量删除
            </el-button>
            <el-button 
              icon="el-icon-close" 
              @click="selectedRows = []"
              size="small"
            >
              取消选择
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @close="handleDialogClose"
      class="role-dialog"
    >
      <el-form
        :model="formData"
        :rules="formRules"
        ref="form"
        label-width="100px"
      >
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="formData.roleCode" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formData.roleName" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="formData.description" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="角色类型" prop="roleType">
          <el-select v-model="formData.roleType" :disabled="isEdit">
            <el-option label="系统角色" value="system" />
            <el-option label="业务角色" value="business" />
          </el-select>
        </el-form-item>
        <el-form-item label="父角色" prop="parentId">
          <el-select v-model="formData.parentId" placeholder="请选择父角色" clearable>
            <el-option
              v-for="role in parentRoleOptions"
              :key="role.id"
              :label="role.roleName"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="formData.sortOrder" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="权限" prop="permissionIds">
          <el-select v-model="formData.permissionIds" multiple placeholder="请选择权限">
            <el-option
              v-for="permission in permissionOptions"
              :key="permission.id"
              :label="permission.permissionName"
              :value="permission.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 角色详情对话框 -->
    <el-dialog
      title="角色详情"
      :visible.sync="detailDialogVisible"
      width="600px"
      class="role-dialog"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="角色编码">{{ currentRole.roleCode }}</el-descriptions-item>
        <el-descriptions-item label="角色名称">{{ currentRole.roleName }}</el-descriptions-item>
        <el-descriptions-item label="描述">{{ currentRole.description }}</el-descriptions-item>
        <el-descriptions-item label="角色类型">
          <el-tag :type="currentRole.roleType === 'system' ? 'primary' : 'success'">
            {{ currentRole.roleType === 'system' ? '系统角色' : '业务角色' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="父角色">{{ currentRole.parentRoleName }}</el-descriptions-item>
        <el-descriptions-item label="用户数量">{{ currentRole.userCount }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentRole.status === 1 ? 'success' : 'danger'">
            {{ currentRole.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentRole.createTime }}</el-descriptions-item>
      </el-descriptions>
      
      <div v-if="currentRole.permissions && currentRole.permissions.length > 0" style="margin-top: 20px;">
        <h4>权限信息</h4>
        <el-tag
          v-for="permission in currentRole.permissions"
          :key="permission.id"
          style="margin-right: 10px; margin-bottom: 10px;"
        >
          {{ permission.permissionName }}
        </el-tag>
      </div>
    </el-dialog>

    <!-- 权限分配对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="permissionDialogVisible"
      width="800px"
      class="role-dialog"
    >
      <div class="permission-assignment">
        <div class="permission-tree">
          <h4>权限树</h4>
          <el-tree
            ref="permissionTree"
            :data="permissionTreeData"
            :props="treeProps"
            show-checkbox
            node-key="id"
            :default-checked-keys="checkedPermissions"
            @check="handlePermissionCheck"
          />
        </div>
      </div>
      <div slot="footer">
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSavePermissions">确定</el-button>
      </div>
    </el-dialog>

    <!-- 角色用户列表对话框 -->
    <el-dialog
      title="角色用户列表"
      :visible.sync="userListDialogVisible"
      width="800px"
      class="role-dialog"
    >
      <div class="user-list-section">
        <div class="user-list-header">
          <h4>{{ currentRole.roleName }} 的用户列表</h4>
          <div class="user-count-info">
            <el-tag type="info" size="small">共 {{ roleUsers.length }} 个用户</el-tag>
          </div>
        </div>
        
        <el-table
          :data="roleUsers"
          stripe
          border
          height="400"
          class="user-table"
        >
          <el-table-column prop="username" label="用户名" width="120" />
          <el-table-column prop="name" label="姓名" width="100" />
          <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />
          <el-table-column prop="phone" label="手机号" width="120" />
          <el-table-column prop="department" label="部门" width="120" />
          <el-table-column prop="position" label="职位" width="120" />
          <el-table-column prop="status" label="状态" width="80" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="small">
                {{ scope.row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="160" />
        </el-table>
      </div>
      
      <div slot="footer">
        <el-button @click="userListDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleManageUsers">管理用户</el-button>
      </div>
    </el-dialog>

    <!-- 复制角色对话框 -->
    <el-dialog
      title="复制角色"
      :visible.sync="copyDialogVisible"
      width="400px"
      class="role-dialog"
    >
      <el-form :model="copyForm" :rules="copyRules" ref="copyForm" label-width="100px">
        <el-form-item label="新角色编码" prop="newRoleCode">
          <el-input v-model="copyForm.newRoleCode" />
        </el-form-item>
        <el-form-item label="新角色名称" prop="newRoleName">
          <el-input v-model="copyForm.newRoleName" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="copyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCopySubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { roleApi } from '@/api/roleManagement'
import { permissionApi } from '@/api/permissionManagement'
import { permissionMixin } from '@/utils/permission'

export default {
  name: 'RoleManagement',
  mixins: [permissionMixin],
  data() {
    return {
      loading: false,
      tableData: [],
      roleTreeData: [],
      selectedRows: [],
      showRoleTree: false,
      searchForm: {
        roleName: '',
        roleType: '',
        status: ''
      },
      pagination: {
        page: 1,
        size: 10,
        total: 0
      },
      dialogVisible: false,
      detailDialogVisible: false,
      permissionDialogVisible: false,
      userListDialogVisible: false,
      copyDialogVisible: false,
      isEdit: false,
      dialogTitle: '新增角色',
      formData: {
        roleCode: '',
        roleName: '',
        description: '',
        roleType: 'business',
        parentId: null,
        sortOrder: 0,
        status: 1,
        permissionIds: []
      },
      formRules: {
        roleCode: [
          { required: true, message: '请输入角色编码', trigger: 'blur' }
        ],
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      parentRoleOptions: [],
      permissionOptions: [],
      currentRole: {},
      permissionTreeData: [],
      checkedPermissions: [],
      currentRoleId: null,
      roleUsers: [], // 角色用户列表
      treeProps: {
        children: 'children',
        label: 'permissionName'
      },
      copyForm: {
        newRoleCode: '',
        newRoleName: ''
      },
      copyRules: {
        newRoleCode: [
          { required: true, message: '请输入新角色编码', trigger: 'blur' }
        ],
        newRoleName: [
          { required: true, message: '请输入新角色名称', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.loadData()
    this.loadParentRoleOptions()
    this.loadPermissionOptions()
    this.loadRoleTree()
  },
  methods: {
    // 加载数据
    async loadData() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.page,
          size: this.pagination.size,
          ...this.searchForm
        }
        const response = await roleApi.getRoles(params)
        
        if (response.code === 200) {
          this.tableData = response.data.content
          this.pagination.total = response.data.total
        } else {
          this.$message.error(response.message || '加载数据失败')
        }
      } catch (error) {
        console.error('角色查询异常:', error)
        this.$message.error('加载数据失败: ' + (error.message || '未知错误'))
      } finally {
        this.loading = false
      }
    },

    // 加载角色树
    async loadRoleTree() {
      try {
        const response = await roleApi.getAllRolesTree()
        if (response.code === 200) {
          this.roleTreeData = response.data
        }
      } catch (error) {
        console.error('加载角色树失败:', error)
      }
    },

    // 加载父角色选项
    async loadParentRoleOptions() {
      try {
        const response = await roleApi.getAllRolesTree()
        if (response.code === 200) {
          this.parentRoleOptions = this.flattenRoles(response.data)
        }
      } catch (error) {
        console.error('加载父角色选项失败:', error)
      }
    },

    // 加载权限选项
    async loadPermissionOptions() {
      try {
        const response = await permissionApi.getAllPermissionsTree()
        if (response.code === 200) {
          this.permissionOptions = this.flattenPermissions(response.data)
        }
      } catch (error) {
        console.error('加载权限选项失败:', error)
      }
    },

    // 扁平化角色树
    flattenRoles(roles) {
      let result = []
      roles.forEach(role => {
        result.push(role)
        if (role.children && role.children.length > 0) {
          result = result.concat(this.flattenRoles(role.children))
        }
      })
      return result
    },

    // 扁平化权限树
    flattenPermissions(permissions) {
      let result = []
      permissions.forEach(permission => {
        result.push(permission)
        if (permission.children && permission.children.length > 0) {
          result = result.concat(this.flattenPermissions(permission.children))
        }
      })
      return result
    },

    // 搜索
    handleSearch() {
      this.pagination.page = 1
      this.loadData()
    },

    // 重置搜索
    handleReset() {
      this.searchForm = {
        roleName: '',
        roleType: '',
        status: ''
      }
      this.pagination.page = 1
      this.loadData()
    },

    // 新增
    handleAdd() {
      this.isEdit = false
      this.dialogTitle = '新增角色'
      this.formData = {
        roleCode: '',
        roleName: '',
        description: '',
        roleType: 'business',
        parentId: null,
        sortOrder: 0,
        status: 1,
        permissionIds: []
      }
      this.dialogVisible = true
    },

    // 编辑
    handleEdit(row) {
      this.isEdit = true
      this.dialogTitle = '编辑角色'
      this.formData = { ...row }
      this.dialogVisible = true
    },

    // 查看
    handleView(row) {
      this.currentRole = row
      this.detailDialogVisible = true
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确定要删除该角色吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await roleApi.deleteRole(row.id)
          if (response.code === 200) {
            this.$message.success('删除成功')
            this.loadData()
            this.loadRoleTree()
          }
        } catch (error) {
          this.$message.error('删除失败')
        }
      })
    },

    // 分配权限
    async handleAssignPermissions(row) {
      this.currentRoleId = row.id
      try {
        // 加载权限树
        const treeResponse = await permissionApi.getAllPermissionsTree()
        if (treeResponse.code === 200) {
          this.permissionTreeData = treeResponse.data
        }

        // 加载角色已有权限 - 使用角色权限预览接口
        const permissionResponse = await roleApi.getRolePermissionPreview(row.id)
        if (permissionResponse.code === 200) {
          // 从预览数据中提取权限ID
          const allPermissions = permissionResponse.data.allPermissions || []
          this.checkedPermissions = allPermissions.map(p => p.id)
        }

        this.permissionDialogVisible = true
      } catch (error) {
        console.error('加载权限数据失败:', error)
        this.$message.error('加载权限数据失败')
      }
    },

    // 权限选择变化
    handlePermissionCheck(data, checkedInfo) {
      // 处理权限选择逻辑
    },

    // 保存权限分配
    async handleSavePermissions() {
      try {
        const checkedKeys = this.$refs.permissionTree.getCheckedKeys()
        const halfCheckedKeys = this.$refs.permissionTree.getHalfCheckedKeys()
        const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys]

        // 使用正确的API格式
        const requestData = {
          roleId: this.currentRoleId,
          permissionIds: allCheckedKeys
        }

        const response = await roleApi.assignPermissionsToRole(requestData)
        if (response.code === 200) {
          this.$message.success('权限分配成功')
          this.permissionDialogVisible = false
          this.loadData()
          this.loadRoleTree()
        } else {
          this.$message.error(response.message || '权限分配失败')
        }
      } catch (error) {
        console.error('权限分配失败:', error)
        this.$message.error('权限分配失败: ' + (error.message || '未知错误'))
      }
    },

    // 分配用户
    handleAssignUsers(row) {
      this.$message.info('分配用户功能开发中...')
    },

    // 查看用户
    async handleViewUsers(row) {
      this.currentRole = row
      try {
        const response = await roleApi.getRoleUsers(row.id)
        if (response.code === 200) {
          this.roleUsers = response.data || []
          this.userListDialogVisible = true
        } else {
          this.$message.error(response.message || '获取用户列表失败')
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        this.$message.error('获取用户列表失败: ' + (error.message || '未知错误'))
      }
    },

    // 管理用户
    handleManageUsers() {
      this.$message.info('用户管理功能开发中...')
      // 这里可以跳转到用户管理页面，并筛选当前角色的用户
      // this.$router.push({ name: 'UserManagement', query: { roleId: this.currentRole.id } })
    },

    // 导出
    handleExport() {
      this.$message.info('导出功能开发中...')
    },

    // 批量启用
    handleBatchEnable() {
      this.$message.info('批量启用功能开发中...')
    },

    // 批量禁用
    handleBatchDisable() {
      this.$message.info('批量禁用功能开发中...')
    },

    // 批量删除
    handleBatchDelete() {
      this.$message.info('批量删除功能开发中...')
    },

    // 复制角色
    handleCopy(row) {
      this.$message.info('复制角色功能开发中...')
    },

    // 提交表单
    handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            let response
            if (this.isEdit) {
              // 编辑时发送更新请求
              const updateData = {
                roleCode: this.formData.roleCode,
                roleName: this.formData.roleName,
                description: this.formData.description,
                roleType: this.formData.roleType,
                parentId: this.formData.parentId,
                sortOrder: this.formData.sortOrder,
                status: this.formData.status,
                permissionIds: this.formData.permissionIds
              }
              response = await roleApi.updateRole(this.formData.id, updateData)
            } else {
              // 新增时发送创建请求
              const createData = {
                roleCode: this.formData.roleCode,
                roleName: this.formData.roleName,
                description: this.formData.description,
                roleType: this.formData.roleType,
                parentId: this.formData.parentId,
                sortOrder: this.formData.sortOrder,
                status: this.formData.status,
                permissionIds: this.formData.permissionIds
              }
              response = await roleApi.createRole(createData)
            }
            
            if (response.code === 200) {
              this.$message.success(this.isEdit ? '更新成功' : '创建成功')
              this.dialogVisible = false
              this.loadData()
              this.loadRoleTree()
            } else {
              this.$message.error(response.message || (this.isEdit ? '更新失败' : '创建失败'))
            }
          } catch (error) {
            console.error('提交失败:', error)
            this.$message.error(this.isEdit ? '更新失败' : '创建失败: ' + (error.message || '未知错误'))
          }
        }
      })
    },

    // 关闭对话框
    handleDialogClose() {
      this.$refs.form.resetFields()
    },

    // 选择变化
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },

    // 分页大小变化
    handleSizeChange(size) {
      this.pagination.size = size
      this.pagination.page = 1
      this.loadData()
    },

    // 当前页变化
    handleCurrentChange(page) {
      this.pagination.page = page
      this.loadData()
    }
  }
}
</script>

<style scoped>
.role-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 页面标题区域 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  flex-direction: column;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-subtitle {
  font-size: 14px;
  opacity: 0.9;
  margin-top: 4px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.header-actions .el-button {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  backdrop-filter: blur(10px);
}

.header-actions .el-button:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
}

/* 搜索区域 */
.search-section {
  margin-bottom: 20px;
}

.search-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-form {
  padding: 10px 0;
}

.search-form .el-form-item {
  margin-bottom: 16px;
}

/* 表格区域 */
.table-section {
  margin-bottom: 20px;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 16px;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.data-table {
  border-radius: 4px;
  overflow: hidden;
}

.data-table .el-table__header {
  background-color: #fafafa;
}

.data-table .el-table__header th {
  background-color: #fafafa !important;
  color: #606266;
  font-weight: 600;
}

/* 树形视图 */
.tree-view {
  padding: 16px 0;
}

.role-tree {
  background: #fafafa;
  border-radius: 4px;
  padding: 16px;
}

.custom-tree-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 8px 0;
}

.tree-node-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.tree-node-actions {
  display: flex;
  gap: 4px;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
  margin-top: 16px;
  border-top: 1px solid #ebeef5;
}

/* 批量操作 */
.batch-actions {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1000;
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateX(-50%) translateY(100%);
  }
  to {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
  }
}

.batch-card {
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border: 1px solid #e4e7ed;
}

.batch-content {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 8px 0;
}

.batch-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  font-size: 14px;
}

.batch-buttons {
  display: flex;
  gap: 8px;
}

/* 对话框优化 */
.role-dialog .el-dialog {
  border-radius: 8px;
}

.role-dialog .el-dialog__header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px 20px 16px;
  border-radius: 8px 8px 0 0;
}

.role-dialog .el-dialog__title {
  color: white;
  font-weight: 600;
}

.role-dialog .el-dialog__headerbtn .el-dialog__close {
  color: white;
}

.role-dialog .el-dialog__body {
  padding: 24px;
}

/* 权限分配 */
.permission-assignment {
  max-height: 400px;
  overflow-y: auto;
}

.permission-tree h4 {
  margin-bottom: 10px;
  color: #303133;
  font-weight: 600;
}

/* 表单优化 */
.el-form-item__label {
  font-weight: 500;
  color: #606266;
}

.el-input__inner,
.el-select .el-input__inner {
  border-radius: 4px;
  transition: all 0.3s ease;
}

.el-input__inner:focus,
.el-select .el-input__inner:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

/* 按钮优化 */
.el-button {
  border-radius: 4px;
  transition: all 0.3s ease;
}

.el-button--primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.el-button--primary:hover {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

/* 标签优化 */
.el-tag {
  border-radius: 4px;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .role-management {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .header-actions {
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    width: 100%;
  }
  
  .table-toolbar {
    flex-direction: column;
    gap: 12px;
  }
  
  .custom-tree-node {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .tree-node-actions {
    flex-wrap: wrap;
  }
  
  .batch-content {
    flex-direction: column;
    gap: 12px;
  }
  
  .batch-buttons {
    flex-wrap: wrap;
    justify-content: center;
  }
}

/* 加载状态优化 */
.el-loading-mask {
  background-color: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(2px);
}

/* 表格行悬停效果 */
.data-table .el-table__row:hover {
  background-color: #f8f9ff !important;
}

/* 空状态优化 */
.el-table__empty-block {
  background-color: #fafafa;
  border-radius: 4px;
}

/* 滚动条优化 */
.data-table::-webkit-scrollbar,
.permission-assignment::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.data-table::-webkit-scrollbar-track,
.permission-assignment::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.data-table::-webkit-scrollbar-thumb,
.permission-assignment::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.data-table::-webkit-scrollbar-thumb:hover,
.permission-assignment::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 用户数量徽章样式 */

/* 用户数量容器样式 */
.user-count-container {
  position: relative;
  padding: 8px 8px 8px 8px; /* 上右下左，给徽章留出空间 */
  overflow: visible !important; /* 确保不被裁剪 */
}



.user-count-badge .el-badge__content {
  z-index: 1000 !important;
  position: absolute !important;
  top: -6px !important; /* 减少向上偏移，避免被裁剪 */
  right: -6px !important;
  min-width: 18px !important;
  height: 18px !important;
  line-height: 18px !important;
  font-size: 12px !important;
  border-radius: 9px !important;
  background-color: #f56c6c !important;
  color: #fff !important;
  border: 2px solid #fff !important;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1) !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
}

.user-count-badge .el-button {
  position: relative;
  z-index: 1;
}

/* 用户列表对话框样式 */
.user-list-section {
  padding: 0;
}

.user-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.user-list-header h4 {
  margin: 0;
  color: #303133;
  font-weight: 600;
  font-size: 16px;
}

.user-count-info {
  display: flex;
  align-items: center;
}

.user-table {
  border-radius: 6px;
  overflow: hidden;
}

.user-table .el-table__header {
  background-color: #f8f9fa;
}

.user-table .el-table__header th {
  background-color: #f8f9fa;
  color: #606266;
  font-weight: 600;
}

/* 视图切换按钮样式 */
.view-toggle-btn {
  border-radius: 6px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.view-toggle-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.view-toggle-btn .el-icon-menu,
.view-toggle-btn .el-icon-s-grid {
  font-size: 14px;
  margin-right: 4px;
}
</style>